// 支付押金
function payCashMoney() {
    orderN = orderNumber + "Y";
    var cashMoney = parseFloat($("#cashMoney").val()) * TableSize;
    var cashPay = $("#cashPay").val();
    if (cashPay == "0") {
        var payURL = "/desk/pay?payMoney=" + cashMoney + "&orderNumber=" + orderN;
        var winObj = window.open(payURL, 'newwindow', 'height=650, width=800, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no')
        $(winObj).on("unload", function () {
            checkPayCash();
        })
    } else {
        $("#payStatusCash").text("已付款")
    }
}

// 验证押金
function checkPayCash() {
    if ($("#cashPay").val() == 1) {
        $("#payStatusCash").text("已付款")
        return;
    }

    orderN = orderNumber + "Y";
    var load = layer.load(2, {shade: 0.1}); //0代表加载的风格，支持0-2
    //窗口关闭时到数据库查询该订单是否付款成功
    $.ajax({
        url: "/room_predict_order/payFind",
        type: 'get',
        dataType: 'json',
        data: {"ordernumber": orderN},
        success: function (data) {
            layer.close(load);
            $("#payStatusCash").text(data.msg);
        },
        error: function () {
            layer.close(load);
            parent.layer.alert("信息获取失败！");
            return;
        }
    });
}

//支付房费
function payRoomMoney() {

    var totalPrice = $("#totalPrice").text();
    var totalPay = $("#totalPay").val();
    if (totalPay == "0") {
        var payURL = "/desk/pay?payMoney=" + totalPrice + "&orderNumber=" + orderNumber;
        var winObj = window.open(payURL, 'newwindow', 'height=650, width=800, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no')
        $(winObj).on("unload", function () {
            checkPayRoom();
        })
    } else {
        $("#payStatusRoom").text("已付款")
    }
}

//验证房费
function checkPayRoom() {
    if ($("#totalPay").val() == 1) {
        $("#payStatusRoom").text("已付款")
        return;
    }

    var load = layer.load(2, {shade: 0.1}); //0代表加载的风格，支持0-2
    //窗口关闭时到数据库查询该订单是否付款成功
    $.ajax({
        url: "/room_predict_order/payFind",
        type: 'get',
        dataType: 'json',
        data: {"ordernumber": orderNumber},
        success: function (data) {
            layer.close(load);
            $("#payStatusRoom").text(data.msg);
        },
        error: function () {
            layer.close(load);
            parent.layer.alert("信息获取失败！");
            return;
        }
    });
}


/**
 * 检查纠正金额样式
 * @param num
 * @returns {string}
 * @constructor
 */
var precapital;
document.querySelector('.capital').addEventListener('focus', function () {
    if (this.value == '0.00') {
        this.value = '';
    } else {
        this.value = this.value.replace(/\.00/, '').replace(/(\.\d)0/, '$1');
    }
    precapital = this.value;
});
document.querySelector('.capital').addEventListener('keyup', function () {

    this.value = this.value.replace(/^[\.]/, '').replace(/[^\d.]/g, '');
    if (this.value.split(".").length - 1 > 1) {
        this.value = precapital;
    }
    precapital = this.value;
});
document.querySelector('.capital').addEventListener('blur', function () {
    this.value = this.value.replace(/[\.]$/, '');
    this.value = this.value.replace(/(.*)\.([\d]{2})(\d*)/g, '$1.$2');
    this.value = Number(this.value).toFixed(2);
    var logNum = this.value.toString();
    if (logNum.match(/\./g) != null) {
        integerNum = parseInt(logNum).toString().replace(/\d(?=(\d{3})+$)/g, '$&,');
        decimalNum = '.' + logNum.replace(/(.*)\.(.*)/g, '$2');
    }
});

// 函数参数必须是字符串，因为二代身份证号码是十八位，而在javascript中，十八位的数值会超出计算范围，造成不精确的结果，导致最后两位和计算的值不一致，从而该函数出现错误。
// 详情查看javascript的数值范围
function checkIDCard(idcode) {
    // 加权因子
    var weight_factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    // 校验码
    var check_code = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

    var code = idcode + "";
    var last = idcode[17];//最后一位

    var seventeen = code.substring(0, 17);

    // ISO 7064:1983.MOD 11-2
    // 判断最后一位校验码是否正确
    var arr = seventeen.split("");
    var len = arr.length;
    var num = 0;
    for (var i = 0; i < len; i++) {
        num = num + arr[i] * weight_factor[i];
    }

    // 获取余数
    var resisue = num % 11;
    var last_no = check_code[resisue];

    // 格式的正则
    // 正则思路
    /*
    第一位不可能是0
    第二位到第六位可以是0-9
    第七位到第十位是年份，所以七八位为19或者20
    十一位和十二位是月份，这两位是01-12之间的数值
    十三位和十四位是日期，是从01-31之间的数值
    十五，十六，十七都是数字0-9
    十八位可能是数字0-9，也可能是X
    */
    var idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;

    // 判断格式是否正确
    var format = idcard_patter.test(idcode);

    // 返回验证结果，校验码和格式同时正确才算是合法的身份证号码
    return last === last_no && format ? true : false;
}


//关闭该层
function closeThis() {
    //向后台发送取消占用该订单号
    $.ajax({
        url: parent.closeModelURL,
        type: 'get',
        data: {"ordernumber": orderNumber},
        dataType: 'json',
        success: function (data) {
        }
    });
    var index = parent.layer.getFrameIndex(window.name);
    parent.layui.table.reload('entityTable');
    parent.layer.close(index);
}

//遮罩层
function showMask() {
    $("#mask").css("height", $(document).height());
    $("#mask").css("width", $(document).width());
    $("#mask").show();
}

function hideMask() {
    $("#mask").hide();
}

//获得日期
function getNewData(dateTemp, days) {
    var dateTemp = dateTemp.split("-");
    //转换为MM-DD-YYYY格式
    var nDates = new Date(dateTemp[0], dateTemp[1], dateTemp[2]);
    var millSeconds = nDates.getTime() + (days * 24 * 60 * 60 * 1000);
    var rDate = new Date(millSeconds);
    var year = rDate.getFullYear();
    var month = rDate.getMonth();
    if (month < 10) month = "0" + month;
    var date = rDate.getDate();
    if (date < 10) date = "0" + date;
    return (year + "-" + month + "-" + date);
}

//格式化日期
function dateFormat(value) {
    if (null != value && "" != value) {
        var date = new Date(value);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        if (m < 10) {
            m = "0" + m;
        }
        var d = date.getDate();
        if (d < 10) {
            d = "0" + d;
        }
        return y + '-' + m + '-' + d;
    } else {
        return "";
    }
}

//计算天数
function GetDateDiff(startDate, endDate) {
    var startTime = new Date(Date.parse(startDate.replace(/-/g, "/"))).getTime();
    var endTime = new Date(Date.parse(endDate.replace(/-/g, "/"))).getTime();
    var dates = Math.abs((startTime - endTime)) / (1000 * 60 * 60 * 24);
    if (dates == 0) {
        dates = 1;
    }
    return dates;
}

//计算总金额
function comTotalMoney() {
    $("#cashMoney").attr("readonly", "readonly");
    var day = parseInt($("#totalDay").html());
    var tprice = parseFloat($(".layui-table-total td[data-field=price] div").html());
    var cash = parseFloat($("#cashMoney").val()) == "NaN" ? 0 : parseFloat($("#cashMoney").val());
    var total = (day * tprice);
    $("#totalPrice").text(total.toFixed(2));
}


//将数据格式化为下拉框中的分组样式
function dateToGroupSelect(data, settings) {
    settings = settings || {};
    var valueField = settings.valueField || 'value',
        textField = settings.textField || 'text',
        selectedValue = settings.selectedValue || "";
    var html = [];
    //声明一个数组
    var rtids = [0];
    for (var i = 0; i < data.length; i++) {
        if (!rtids.includes(data[i].rtid)) {
            rtids.push(data[i].rtid);
        }
    }
    for (var j = 0; j < rtids.length; j++) {
        for (var i = 0, item; i < data.length; i++) {
            if (rtids[j] == data[i].rtid) {
                html.push('<optgroup label="' + data[i].rtname + '">')
                for (var i = 0, item; i < data.length; i++) {
                    if (rtids[j] == data[i].rtid) {
                        item = data[i];
                        html.push('<option value="');
                        html.push(item[valueField]);
                        html.push('"');
                        if (selectedValue && item[valueField] == selectedValue) {
                            html.push(' selected="selected"');
                        }
                        html.push('>');
                        html.push(item[textField]);
                        html.push('</option>');
                    }
                }
                html.push('</optgroup>');
                break;
            }
        }
    }
    return html.join('');
}
